package com.gao.handler;

import com.alibaba.fastjson.JSON;
import com.gao.manager.jwt.JwtKeeper;
import com.gao.util.JwtUtils;
import com.gao.util.ResultVO;
import com.gao.util.WebUtils;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author gao
 * @time 2022/11/05 11:36:50
 */
@Component
@RequiredArgsConstructor
public class JsonAuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @NonNull
    private JwtKeeper jwtKeeper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        String jwt = JwtUtils.createToken(obtainUsernameFromSecurityContext(), 3600);
        String json = WebUtils.generateSuccessJson("认证成功", jwt);
        WebUtils.renderString(httpServletResponse, json);
        jwtKeeper.add(jwt);
    }

    private String obtainUsernameFromSecurityContext() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserDetails userDetails = (UserDetails) principal;
        return userDetails.getUsername();
    }

}